#include "textstatusmonitor.h"
#include "ui_textstatusmonitor.h"

#include <QScrollBar>

TextStatusMonitor::TextStatusMonitor(QPlainTextEdit* textEidt, QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::TextStatusMonitor)
    , mTextEdit(textEidt)
{
    setAttribute(Qt::WA_DeleteOnClose);
    ui->setupUi(this);
    ui->progressBar->setFormat("%p%");
    ui->progressBar->setValue(0);
    Init();
    ConnectAll();
}

TextStatusMonitor::~TextStatusMonitor()
{
    delete ui;
}

void TextStatusMonitor::Init()
{
    UpdateFontLabel();
    UpdatePosLabel();
    UpdateTotalNumberLabel();
    UpdateProgressBar();
}

void TextStatusMonitor::ConnectAll()
{
    if (mTextEdit == nullptr) {
        qDebug("warning! mTextEdit == nullptr");
        return;
    }

    connect(mTextEdit, &QPlainTextEdit::selectionChanged, this, &TextStatusMonitor::UpdateFontLabel);
    connect(mTextEdit, &QPlainTextEdit::cursorPositionChanged, this, &TextStatusMonitor::UpdatePosLabel);
    connect(mTextEdit, &QPlainTextEdit::textChanged, this, &TextStatusMonitor::UpdateTotalNumberLabel);
    connect(mTextEdit, &QPlainTextEdit::textChanged, this, &TextStatusMonitor::UpdateProgressBar);
    connect(mTextEdit->verticalScrollBar(), &QScrollBar::valueChanged, this, &TextStatusMonitor::UpdateProgressBar);
}

void TextStatusMonitor::UpdatePosLabel()
{
    // 获取行号和列号
    auto cursor = mTextEdit->textCursor();
    int line = cursor.blockNumber() + 1; // 行号从 1 开始
    int column = cursor.positionInBlock() + 1; // 列号从 1 开始
    ui->posLabel->setText("行 " + QString::number(line) + ", 列 " + QString::number(column));
}

void TextStatusMonitor::UpdateTotalNumberLabel()
{
    ui->totalNumberLabel->setText(QString::number(mTextEdit->toPlainText().length()) + " 个字符");
}

void TextStatusMonitor::UpdateProgressBar()
{
    const auto scroll = mTextEdit->verticalScrollBar();
    if (scroll == nullptr) {
        return;
    }
    ui->progressBar->setValue(scroll->maximum() == 0 ? 100 : static_cast<double>(scroll->value()) / scroll->maximum() * 100);
}


void TextStatusMonitor::UpdateFontLabel()
{
    auto fmt = mTextEdit->currentCharFormat();
    ui->fontLabel->setText("字体: " + fmt.font().family());
}
